
export default {
  // 为当前模块开启命名空间
  namespaced: true,
 
  // 模块的 state 数据
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
 
  // 模块的 mutations 方法
  mutations: {
    addToCart(state, goods){
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id)
      if(!findResult){
        state.cart.push(goods)
      }else{
        findResult.goods_count++
      }
      this.commit('m_cart/savetoStorage');
      console.log('state.cart: ', state.cart)
    },
    savetoStorage(state){
      uni.setStorageSync('cart', JSON.stringify(state.cart));
    },
    updateGoodsState(state, goods){
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id);
      if(findResult){
        findResult.goods_state = goods.goods_state;
        this.commit('m_cart/savetoStorage');
      }
    },
    // 更新购物车中商品的数量
    updateGoodsCount(state, goods){
      const findResult = state.cart.find(x => x.goods_id == goods.goods_id);
      if(findResult){
        findResult.goods_count = goods.goods_count;
        this.commit('m_cart/savetoStorage');
      }
    },
    removeGoodsById(state, goods){
      state.cart = state.cart.filter(x => x.goods_id != goods.goods_id);
      this.commit('m_cart/savetoStorage');
    },
    //更新所有商品勾选状态
    updateAllGoodsState(state, paramState){
      state.cart.forEach(x => x.goods_state = paramState)
      this.commit('m_cart/savetoStorage');
    }
  },
 
  // 模块的 getters 属性
  getters: {
    total(state){
      let c = 0;
      state.cart.forEach(goods => c = c + goods.goods_count)
      return c
    },
    checkedCount(state){
      //filter() 从购物车过滤已勾选商品
      let array = state.cart.filter(x => x.goods_state);
      //reduce() 将已勾选商品总数累加, 返回值为已勾选商品总数
      let count = array.reduce((total, item) => {
        total = total + item.goods_count;
          return total;
      }, 0)
      return count
    },
    checkedGoodsAmount(state){
      let array = state.cart.filter(x => x.goods_state);
      let price = array.reduce((totalPrice, item) => {
        totalPrice = totalPrice + item.goods_count * item.goods_price;
        return totalPrice;
      }, 0)
      return price
    }
  },

}